<?php
/**
 * Created by YuanXiShop.
 * User: YuanXi
 * Date: 2021/6/3 0003
 * Time: 1:26
 */

namespace admin;


use models\BaseDao;

use lmonkey\CatTree as CT;

class Category extends Admin
{
    function __construct()
    {
        parent::__construct();

        $this->assign('menumark','category');

        //获取数据库操作对象
        $db = new BaseDao();

        //获取全部商品分类，并按ord排序
        $data = $db->select('category','*',['ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

        $cats = CT::getList($data);

        //将数据分配给模板
        $this->assign('cats',$cats);
    }
    function index()
    {
        //标题
        $this->assign('title','文章分类列表');
        //输出模板
        $this->display('category/index');
    }
    function add()
    {
        if($_POST['do_submit']){
            $db = new BaseDao();
            unset($_POST['do_submit']);
            if($db->insert('category',$_POST)){
                $this->success('/admin/category','添加成功！');
            }else{
                $this->error('/admin/category','添加失败！');
            }
        }
        $this->assign('title','商品分类添加');
        $this->display('category/add');
    }
    function mod($id)
    {
        $db = new BaseDao();

        $data = $db->get('category','*',['id'=>$id]);

        //传递子分类
        $this->assign('childs',$_GET['childs']);

        $this->assign($data);

        $this->assign('title','修改文章分类');

        $this->display('category/mod');
    }
    function doupdate()
    {
        $id = $_POST['id'];

        unset($_POST['id']);

        $_POST['childs'] .= $id;

        if(in_array($_POST['pid'],explode(',',$_POST['childs']))){
            $this->error('/admin/category','不允许把自己传入自己分类或者自己的子类下...');
            exit;
        }

        unset($_POST['childs']);

        $db = new BaseDao();

        if($db->update('category',$_POST,['id'=>$id])){
            $this->success('/admin/category','修改成功！');
        }else{
            $this->error('/admin/category/mod/'.$id,'修改失败！');
        }
    }
    function del($id)
    {
        if($_GET['childs'] != ''){
            $this->error('/admin/category','请先删除子类...');
            exit;
        }
        $db = new BaseDao();
        if($db->delete('category',['id'=>$id])){
            $this->success('/admin/category','删除成功！');
        }else{
            $this->error('/admin/category','删除失败！');
        }
    }
    function order()
    {
        $db = new BaseDao();
        $num = 0;
        foreach ($_POST['ord'] as $id=>$ord){
            $num += $db->update('category',['ord'=>$ord],['id'=>$id]);
        }
        if($num > 0){
            $this->success('/admin/category','重新排序成功！');
        }else{
            $this->error('/admin/category','重新排序失败！');
        }
    }
}